package com.utils;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.awt.*;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ClassName: PointTypeHandler
 * Description:
 *      自定义类型处理器,用于处理在Mybatis中处理Point类型
 * @author L_Z_R
 * @version 1.0
 * @create 2025/05/20 09:30
 */
@MappedTypes(Point.class)
@MappedJdbcTypes(JdbcType.OTHER)
public class PointTypeHandler extends BaseTypeHandler<Point> {
    // 将 Point 写入数据库
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Point parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.x + "," + parameter.y); // 存储为 "x,y" 格式
    }

    // 从 ResultSet 中按列名获取 Point
    @Override
    public Point getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String[] parts = rs.getString(columnName).split(",");
        return new Point(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    // 从 ResultSet 中按列索引获取 Point
    @Override
    public Point getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String[] parts = rs.getString(columnIndex).split(",");
        return new Point(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    // 从 CallableStatement 中获取 Point
    @Override
    public Point getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String[] parts = cs.getString(columnIndex).split(",");
        return new Point(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }
}
